package com.haipumi.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.haipumi.utils.CommonData;

/*
 * 权限过滤器主要是看session中是否存在某个值
 */
public class LoginFilter implements Filter {
	private String error="404.html";
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		//获取登陆信息
		HttpServletRequest request=(HttpServletRequest) arg0;
		HttpServletResponse response=(HttpServletResponse) arg1;
		HttpSession session=request.getSession();
		//取出当前的路径, 判断是backadmin 还是backcust
		StringBuffer sb=request.getRequestURL();
		if(sb.toString().indexOf("/backcust/")>0){
			//证明访问的是/backcust下的资源
			if(session.getAttribute(CommonData.USERSESSION)!=null){
				arg2.doFilter(arg0, arg1);
			}else{
				//输出信息提示 没有权限
				response.sendRedirect("../Login.jsp");
			}
		}else if(sb.toString().indexOf("/backadmin/")>0){
			//证明访问的是/backcust下的资源
			if(session.getAttribute(CommonData.ADMINSESSION)!=null){
				arg2.doFilter(arg0, arg1);
			}else{
				//输出信息提示 没有权限
				response.sendRedirect("../BackadminLogin.jsp");
			}
		}else if(sb.toString().indexOf("/customerService/")>0){
			//证明访问的是/backcust下的资源
			if(session.getAttribute(CommonData.CUSTOMERSERVICESESSION)!=null){
				arg2.doFilter(arg0, arg1);
			}else{
				//输出信息提示 没有权限
				response.sendRedirect("../BackadminLogin.jsp");
			}
		}
		
		
		
		
//		//从当前session中获取当前登陆用户信息,如果没有则说明该用户没有登陆
//		if(session.getAttribute("currentLogin")==null){
//			
//			//告诉客户端浏览器,回送的数据类型和编码
//			response.setContentType("text/html;charset=utf-8");
//			
//			PrintWriter out=response.getWriter();
//			String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
//			out.print("<script>alert('请先登陆...');location.href='"+basePath+error+"';</script>");
//			out.flush();
//			out.close();
//		}else{
//			//将请求传递给后面的过滤器
//			arg2.doFilter(arg0, arg1);
//		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		if(arg0.getInitParameter("error")!=null){//如果有配置参数
			error=arg0.getInitParameter("error");//将配置错误的页面赋给error
		}
	}

}
